layui.use('table', function () {
    var table = layui.table;
    table.render({
        elem: '#test'
        , url: 'http://localhost:8080/admin/selectacoupon'
        , id: 'couponId'
        , toolbar: '#toolbarDemo' //开启头部工具栏，并为其绑定左侧模板
        , title: '用户数据表'
        , cols: [[
            {type: 'checkbox', fixed: 'left'}
            , {field: 'couponImg', title: '优惠券图片', templet: '#img', width: 112}
            , {field: 'couponId', title: '优惠券编号', width: 118}
            , {field: 'couponDate', title: '修改时间', width: 120}
            , {field: 'couponMoney', title: '优惠券金额', width: 190, sort: true}
            , {field: 'couponHolding', title: '持有天数', width: 128, sort: true}
            , {field: 'couponType', title: '优惠券类型', width: 148, sort: true}
            , {fixed: 'right', title: '操作', toolbar: '#barDemo', width: 194}
        ]]
        , page: { //支持传入 laypage 组件的所有参数（某些参数除外，如：jump/elem） - 详见文档
            layout: ['prev', 'page', 'next', 'skip', 'count'] //自定义分页布局
            // ,groups: 3 //只显示 1 个连续页码
            // ,first: '首页' //不显示首页
            // ,last: '尾页' //不显示尾页
            , theme: '#7185a2'
        }
    });


    //头工具栏事件
    table.on('toolbar(test)', function (obj) {
        var checkStatus = table.checkStatus(obj.config.id);
        switch (obj.event) {
            case 'getCheckLength':
                var data = checkStatus.data;
                layer.msg('选中了：' + data.length + ' 个');
                break;
            case 'isAll':
                layer.msg(checkStatus.isAll ? '全选' : '未全选');
                break;
        }
    });

    //监听行工具事件
    table.on('tool(test)', function (obj) {
        var data = obj.data;
        if (obj.event === 'del') {
            layer.confirm('真的删除行么', function (index) {
                obj.del();
                dlevalue(obj.data.couponId)
                layer.close(index)
            });
        } else if (obj.event === 'edit') {
            // 如果input标签里值为空则赋值为""，否则返回为本值
            let couMoney = inputvalue(obj.data.couponMoney)
            let couHold = inputvalue(obj.data.couponHolding)
            let couType = inputvalue(obj.data.couponType)

            localStorage.setItem("couponMoney", couMoney)
            localStorage.setItem("couponHolding", couHold)
            localStorage.setItem("couponType", couType)

            layer.alert(
                '<form class="layui-form layui-form-pane" action="">\n' +
                '    <div class="layui-form-item">\n' +
                '        <label class="layui-form-label" style="width: 117px;">优惠券金额</label>\n' +
                '        <div class="layui-input-block">\n' +
                '            <input type="text" id="couponMoney" name="couponMoney" lay-verify="title" autocomplete="off" placeholder="请输入优惠券金额" class="layui-input" style="width: 206px"></div>\n' +
                '        <p id="moneyErr" style="color: #b1191a"></p>\n' +
                '    </div>\n' +
                '    <div class="layui-form-item" style="margin-top: 15px">\n' +
                '        <label class="layui-form-label" style="width: 117px" >持有天数</label>\n' +
                '        <div class="layui-input-block">\n' +
                '            <input type="text" id="couponHolding" name="couponHolding" lay-verify="title" autocomplete="off" placeholder="请输入优惠券能持有的天数" class="layui-input" style="width: 206px"></div>\n' +
                '        <p id="holdErr" style="color: #b1191a"></p>\n' +
                '    </div>\n' +
                '    <div class="layui-form-item" style="margin-top: 15px">\n' +
                '        <label class="layui-form-label" style="width: 117px" >优惠券类型</label>\n' +
                '        <div class="layui-input-block">\n' +
                '            <input type="text" id="couponType" name="couponType" lay-verify="title" autocomplete="off" placeholder="请输入优惠券的类型" class="layui-input" style="width: 206px"></div>\n' +
                '        <p id="typeErr" style="color: #b1191a"></p>\n' +
                '    </div>\n' +
                '</form>\n' +
                '<script>\n' +
                '    $("#couponMoney").val(localStorage.getItem("couponMoney"))\n' +
                '    $("#couponHolding").val(localStorage.getItem("couponHolding"))\n' +
                '    $("#couponType").val(localStorage.getItem("couponType"))\n' +
                '</script>',
                {
                    title: '修改表单',
                    type: 0,
                    skin: 'layui-layer-molv', //样式类名
                    closeBtn: 1, //显示关闭按钮
                    anim: 0,  // 动画
                    shadeClose: true, //开启遮罩关闭
                    area: ['380px', '300px'],
                }, function () {

                    // 类型点击确定并未填值
                    strjudge($("[name='couponType']").val())
                    // 类型填值并移动聚焦
                    $("#couponType").blur(function () {
                        strjudge($(this).val())
                    })

                    //  金额未填值并提交
                    numjudge($("[name='couponMoney']").val(), "#moneyErr")
                    // 金额填值并移动聚焦
                    $("#couponMoney").blur(function () {
                        numjudge($(this).val(), "#moneyErr")
                    })

                    //  持有天数未填值并提交
                    numjudge($("[name='couponHolding']").val(), "#holdErr")
                    // 持有天数并移动聚焦
                    $("#couponHolding").blur(function () {
                        numjudge($(this).val(), "#holdErr")
                    })

                    //  得到售后ID对数据库进行更改
                    alliskey(obj.data.couponId)

                }
            )
        }
    });
});

function inputvalue(value) {
    if (value === null) {
        return value = ""
    } else {
        return value
    }
}

function dlevalue(deletId) {
    $.getJSON("http://localhost:8080/admin/delecou", "couponId=" + deletId, function (data) {
        showResult(data)
    })
}

function numjudge(num, p) {

    let ret = /^[0-9]+$/
    if (ret.test(num)) {
        $(p).html("")
        return true
    } else {
        $(p).html("输入有误")
        return false
    }

}

function strjudge(str) {

    let reg = new RegExp("[\\u4E00-\\u9FFF]+", "g")
    if (reg.test(str)) {
        $("#typeErr").html("")
        return true
    } else {
        $("#typeErr").html("输入有误")
        return false
    }

}

function alliskey(couponId) {

    let couponType = $("#couponType").val()
    let couponMoney = $("#couponMoney").val()
    let couponHolding = $("#couponHolding").val()

    if (strjudge(couponType) && numjudge(couponMoney, "#moneyErr") && numjudge(couponHolding, "#holdErr")) {

        // console.log("couponId -> " + couponId)
        // console.log("couponType -> " + couponType)
        // console.log("couponMoney -> " + couponMoney)
        // console.log("couponHolding -> " + couponHolding)

        couponMoney = parseInt(couponMoney)
        couponHolding = parseInt(couponHolding)

        // console.log("couponId -> " + (typeof couponId))
        // console.log("couponType -> " + (typeof couponType))
        // console.log("couponMoney -> " + (typeof couponMoney))
        // console.log("couponHolding -> " + (typeof couponHolding))

        $.ajax({
            url: "http://localhost:8080/admin/updatecou",
            data: "couponId=" + couponId + "&couponMoney=" + couponMoney + "&couponHolding=" + couponHolding + "&couponType=" + couponType,
            dataType: "json",
            type: "get",
            success: function (data) {
                showResult(data)
            }
        })
    }
}

function showResult(data) {
    if (data.code === 0) {
        layer.alert('<div style="height: 45px;text-align:center;line-height: 45px">操作成功</div>', {
            title: '提示',
            skin: 'layui-layer-lan'
            , closeBtn: 0
        }, function (index) {
            layer.close(index)
            layuireload()
        })
    } else {
        layer.alert('<div style="height: 45px;text-align:center;line-height: 45px">操作失败</div>', {
            title: '提示',
            skin: 'layui-layer-lan'
            , closeBtn: 0
        })
    }
}

function layuireload() {

    layui.table.reload('couponId', {
        url: 'http://localhost:8080/admin/selectacoupon'
        , page: {
            cuur: $(".layui-laypage-skip .layui-input").val()
        }
    });
}